<?php

namespace app\common\model;
use think\Model;
use think\Db;
use app\common\model\Prt;
use app\common\model\CorePayLog;
class Member extends Model {
	protected $name = 'member';

	// 开启自动写入时间戳
	protected $autoWriteTimestamp = false;
	
/**
 * 付款后处理
 */
function dopay($out_trade_no){
		$paylog=db("mall_paylog")->where('sn', $out_trade_no)->select();
		$member=db("member")->find($paylog[0]['uid']);	//付款用户
		$module=$paylog[0]['type'];//pay代理join加盟商order订单
		$distibution=getDisbution();//获取分销设置
		$total_fee=0;//向会员上级累计返款
		if($module=='diancan'){//点餐修改订单为待消费
			db("mall_order")->where('sn',  $out_trade_no)->update(['order_state' =>'13']);
			db("mall_paylog")->where('sn', $out_trade_no)->update(['status' =>'2']);
		}elseif($module=='yuyue'){//点餐预约支付
			db("mall_order")->where('sn',  $out_trade_no)->update(['order_state' =>'15']);
			db("mall_paylog")->where('sn', $out_trade_no)->update(['status' =>'2']);
		}elseif($module=="pay"){//代理付款
			//分销
			db("member")->where('id', $member['id'])->update(['distribution_type' => '2']);
			//将普通店铺修改为vip店铺
			db("mall_agent")->where('u_id', $member['id'])->update(['agent_type' => '2']);
			//计算合伙人佣金 
			$p_money = intval($paylog[0]['price']) - (intval($distibution['1_money']) +intval($distibution['2_money']));
			$p_msg = '线下会员'.$member['mobile'].'成功申请vip店铺,获得合伙人佣金';
			//获取合伙人信息
			$pt_info = db('member')->where('id',$member['pt_id'])->find();
			//检查合伙人已推广数量
			$total_num =200  * intval($pt_info['levle_pt']);
			if(intval($pt_info['store_num']) <$total_num){
				$this->vip_yongj($member['pt_id'],$p_money,$p_msg);
				//更新推广店铺数量
				db('member')->where('id',$member['pt_id'])->setInc('store_num',1); 
			}else{
				$this->vip_yongj(0,$p_money,$p_msg);
			}
			//一级代理佣金
			$one_money = intval($distibution['1_money']);
			$one_msg = '线下会员 '.$member['mobile'].' 成功申请vip店铺,获得一级代理佣金';
			$this->vip_yongj($member['pid'],$one_money,$one_msg);
			//二级代理佣金
			$two_money = intval($distibution['2_money']);
			$two_msg = '线下会员 '.$member['mobile'].' 成功申请vip店铺,获得二级代理佣金';
			//获取二级代理id
			$two_pid = db('member')->where('id',$member['pid'])->value('pid');
			$this->vip_yongj($two_pid,$two_money,$two_msg);
			//用户申请加盟商成功
			db('member')->where('id', $member['id'])->update(['is_business' =>2]);
			//更新支付成功日志
			$this->add_corepaylog($paylog[0]['sn']);
		}elseif($module=="join"){//申请为合伙人
			//跟新系统账号余额
			db('member')->where('id',2)->setInc('credit3',$paylog[0]['price']); 
			$msg = '获得会员 '.$member_info['mobile'].' 成功申请合伙人,获得合伙人佣金';
			//用户余额变化日志
			money_change(2,0,'credit2',$paylog[0]['price'],$msg,1,1,0);
			//消息
	 		msg_change(2,3,$msg,0,$status=2);
		}elseif($module=="order"){//修改订单状态
				for($i=0;$i<count($paylog);$i++){
					$order=db("mall_order")->where('id', $paylog[$i]['order_ids'])->find();
					db("mall_paylog")->where('sn', $out_trade_no)->update(['status' => '2']); 
					$order_state=7;
					if($order["express_type"]==1){
						$order_state=3;
					}
					if($order['goods_lanmu']==4){//拼团
						$order_state=2;
					}
					$score="0";
					if($order['give_score']){
						$score='+'.$score;
					}
					if($order['need_score']){
						$score='-'.$score;
					}
					$update_data = array(
						'member1'		=>$order['level1'],
						'member2'		=>$order['level2'],
						'member3'		=>$order['level3'],
						'price1'		=>$order['level1_money'],
						'price2'		=>$order['level2_money'],
						'price3'		=>$order['level3_money'],
						'pt_id'			=>$order['pt_id'],
						'pt_price'		=>$order['pt_money'],
						'co_id'			=>$order['co_id'],
						'co_price'		=>$order['co_money'],
						'score'			=>$score,
						'status'		=>2
					);
					db("mall_paylog")->where('sn', $out_trade_no)->update($update_data);
					$result = db('mall_order')
								->where('id', $order['id'])
								->update(['order_state' => $order_state,'update_time'=>now_time(),'pay_type' =>$paylog[$i]['pay_type'] ,'pay_mode'=>$paylog[$i]['user_type'],'pay_time'=>now_time()]);
					
					$order_memeber = db("member")->where('id', $order['user_id'])->find();
					
					//付款成功更新日志
					//$this->pay_over($order,$order_memeber);

					if($result){
						if($order['goods_lanmu'] !=4){//非拼团的订单打印
							$prt=new Prt();	
							$prt->print_order($paylog[$i]);
							if($paylog[$i]['pay_type']!=1){
								Header('Location:'.config('WEB_DOMAIN').'member/orders.html');
								exit;
							}
						}else{
							$order_item=db("mall_order_item")->where("order_id",$order['id'])->find();
							$tuan_id=$order_item['tuan_id'];
							$goods=db('line_goods')->find($order_item['goods_id']);
							if($tuan_id){//参团
								$pintuan=db('mall_join_pintuan')->find($tuan_id);
								$need=$pintuan['need']-1;
							}else{//开团
								$tuan_id=0;
								$need=$goods['ptneed_person']-1;
							}
							$data=['pid'=>$tuan_id,'uname'=>$member['nick_name']?$member['nick_name']:$member['real_name'],'need'=>$need,'order_id'=>$order['id'],'uid'=>$order['user_id'],'goods_id'=>$order_item['goods_id'],'add_time'=>now_time()];
							if($need==0){//修改拼团状态成功订单状态
									$pt_update['need']=0;
									$pt_update['status']=2;
									db("mall_join_pintuan")->where("id",$tuan_id)->whereOr("pid",$tuan_id)->update($pt_update);
									$pts=db("mall_join_pintuan")->where("id",$tuan_id)->whereOr("pid",$tuan_id)->select();
									$order_ids=array();
									if($pts){
										foreach($pts as $k=>$v){
											$order_ids[]=$v['order_id'];
										}
										$res_order=db("mall_order")->where("id","in",$order_ids)->update(['order_state'=>3]);
									}									
							}else{
								if($tuan_id){//参团减少参团所需人数
									db("mall_join_pintuan")->where("id",$tuan_id)->whereOr("pid",$tuan_id)->setDec('need',1);
								}
							}
							$res_pt=db('mall_join_pintuan')->insert($data);
							$redirect_url=config('WEB_DOMAIN')."tuan_cg.html?pid=$tuan_id&need=$need&goods_id=".$order_item['goods_id'];
							if($paylog[$i]['pay_type']==3){//支付宝回调页面
								Header("Location: $redirect_url");
								exit;
							}else{
								return $redirect_url;
							}
						}
					}else{
						return false;
					}
				}
		
		}elseif($module=="gathering"){
			//记录商家资金变化，更新商家余额
			$this->insbalch($paylog['tid'],"商家面对面收款",$paylog['price'],8,$paylog['sn'],$from=1);
			
			//更新收款记录
			//获取收，付人信息
			$s_agent = db('mall_agent')->where('id', $paylog['tid'])->find();
			$f_user = db('member')->where('id', $paylog['uid'])->find();
			$data = array();
			$data['uid'] 		= $s_agent['id'];
			$data['name'] 		= $s_agent['store_name'];
			$data['mobile1'] 	= $s_agent['store_tel'];
			$data['pay_type'] 	= $paylog['pay_type'];
			$data['money'] 		= $paylog['price'];
			$data['add_time'] 	= now_time();
			$data['status'] 	= 1;
			$data['usid'] 		= $f_user['id'];
			$data['usname'] 	= $f_user['nick_name'];
			$data['mobile2'] 	= $f_user['mobile'];
			
			db('mall_recelog')->insert($data);
			
			//更新用户资金变化表
			$credits_info = array();
			$credits_info['uid']  		= $paylog['uid'];
			$credits_info['tid']  		= $paylog['sn'];
			$credits_info['credittype'] = "credit2";
			$credits_info['price']  	= $paylog['price'];
			$credits_info['add_time']  	= now_time();
			$credits_info['remark']  	= "商家面对面收款";
			$credits_info['type']  		= 4;
			$credits_info['is_pt']  	= 0;
			
			db('mall_credits')->insert($credits_info);
			
			//修改支付状态
			$cut_paylog = array();
            $cut_paylog['status'] = 2;
            $cut_paylog['title'] = "商家面对面收款";
			db("mall_paylog")->where('id', $paylog['id'])->update($cut_paylog);
		}
	return $member;
}
/**
 * 代理申请支付完成后生成新的支付日志
 */
function add_corepaylog($sn){
	$paylog=db("mall_paylog")->where('sn', $sn)->find();
	$corepaylog=new CorePayLog();
	unset($paylog['id']);
	$res=$corepaylog->allowField(true)->save($paylog);
	return $res;
}
/**
 * 确认收货根据订单id生成支付记录
 */
function add_corepaylog1($order_id){
	$paylog=db("mall_paylog")->where('order_ids', $order_id)->order("add_time desc ") ->find();
	$corepaylog=new CorePayLog();
	unset($paylog['id']);
	$res=$corepaylog->allowField(true)->save($paylog);
	return $res;
}
//会员上级返现
function fanxian_pay($paylog_id,$nickname="",$uid,$parent_id=NULL,$level=1,$distibution,&$total_fee){
    if($level <= 3){		
        if(is_null($parent_id)){
            $parent_id = db("member")->where("id",$uid)->column('pid');
            if(empty($parent_id)){
                return false;
            }
        }
		$member = db('member')->where('id',$parent_id)->find();        
        if($member['distribution_type'] == 2){
            $price =$distibution[$level.'_money']; 
			$total_fee+=$price;
            $this->mc_credit_inc($member, 'credit2', $price, 0, '下级会员：'.$nickname.'支付申请合伙人成功奖励余额佣金',1);
            $paylog = array();
            $paylog['member'.$level] = $parent_id;
            $paylog['price'.$level] = $price;
			db("mall_paylog")->where('id', $paylog_id)->update($paylog);
            
//          $notice = '下级会员：'.$nickname.'支付申请合伙人成功奖励余额佣金'.$price;
//          mc_notice($notice,3,$parent_id);
        }
        if($member['pid']){
        	$this->fanxian_pay($paylog_id,$member['mobile'],$uid,$member['pid'],$level+1,$distibution,$total_fee);
        }
    }
}
	//订单收货向上级返现
	function mc_fanxian($nickname, $order,  $level = 1) {
		if ($level <= 3) {
	   	  $member = db('member')->find($order["level".$level]);        
		  if($member['distribution_type'] == 2){
				  $price =$order["level".$level.'_money'];
	              $this->mc_credit_inc($member, 'credit3', $price, 0, '下级会员：'.$nickname.'商品销售奖励佣金',1,0,1);
	      }
		  if($level<3){
		  	if($order["level".($level+1).'_money']!=0){
	      	  $this->mc_fanxian($nickname,$order,$level+1);
	     	}
		  }
		}
	}
	//记录代理商积分变化日志
/**
 *int 			$agent_id	商户ID
 *string 		$message	余额变化说明
 *int			$score	积分变化的值（可为正数或者负数）
 *boolean
 */
function insscoch($agent_id,$message,$score,$type,$tid=0){
	$agent =db('mall_agent')->find($agent_id); 
	if($agent){			
		$data = array();
		$data['agent_id'] = $agent_id;
		$data['message'] = $message;
		$data['type'] = $type;
		$data['tid'] = $tid;
		$data['score'] = $score;
		$data['add_time'] = now_time();
		db('mall_score_charge')->insert($data);
		$res=Db::execute('update long_mall_agent set `score` = `score` + '.$score.' where id = '.$agent_id);
		return $res;
	}else{
		return false;
	}
}
/**
 * 添加线上会员
 */
function add($mobile,$pid){
	$member = db('member')->where('mobile',$mobile)->find();
	if(!$member){
		$data['add_time'] = now_time();
		$data['mobile'] = $mobile;
		$data['pid'] =$pid;
		$data['password']=md5_salt(substr(input('mobile'), -6));
		$data['pay_password']=md5_salt(substr(input('mobile'), -6));
		$result = db('member')->insert($data);
	}   
}
	/**
	 * 记录用户金额变化
	 */
	function mc_credit_inc($member, $credittype, $value, $operator = 0, $remark = '',$type=0,$tid=0,$is_pt=0,$order_id=0){
		$credit = floatval($member[$credittype]);
		if ($credit >= 0 && ($credit + $value >= 0)) {
			$data = array($credittype => $credit + $value);
			$res=db("member")->where("id",$member['id'])->update($data);//更新用户金额
		} //else {
			//return error('-1',"{$creditname}不足,无法操作");
		//}
		$data = array(
			'uid' => $member['id'],
			'credittype' => $credittype,
			'price' => currency_format($value),
			'add_time' => now_time(),
			'operator' => intval($operator),
			'remark' => $remark,
		    'type' => $type,
		    'tid' => $tid,
		    "is_pt"=>$is_pt,
		    "order_id"=>$order_id
		);
		db('mall_credits')->insert($data);
		
		if($type == 1 && $credittype == 'credit2'){
		    Db::execute('update long_member set `all_balance` = `all_balance` + '.$value.' where id = '.$member['id']);
		}
		return true;
	}
	//记录代理商余额变化日志
	/**
	 *int 			$agent_id	商户ID
	 *string 		$message	余额变化说明
	 *float(10,2)	$balance	余额变化的值（可为正数或者负数）
	 *boolean 
	 */
	function insbalch($agent_id,$message,$balance,$type,$tid=0,$from=1){
		$agent =db('mall_agent')->find($agent_id); 
		if($agent){			
			$data = array();
			$data['agent_id'] = $agent_id;
			$data['message'] = $message;
			$data['type'] = $type;
			$data['tid'] = $tid;
			$data['balance'] = sprintf("%.2f",$balance);
			$data['add_time'] = now_time();
			$data['from'] = $from;
			db('mall_charge')->insert($data);
			$res=Db::execute('update long_mall_agent set `store_balance` = `store_balance` + '.$balance.' where id = '.$agent_id);
			return $res;
		}
	}
		
	/**
	 * 记录总代理余额变化日志
	 * @param int $uid			总代理商ID
	 * @param string $message	余额变化明细
	 * @param float $balance	变化余额的值
	 */
	function insbalchuser($uid,$message,$balance,$type,$tid=0){
		$user = $this->find($uid);
			if($user){
				$data = array(
				'uid' => $uid,
				'credittype' => 'credit2',
				'price' => $balance,
				'add_time' => now_time(),
				'operator' => 0,
				'remark' => $message,
			    'type' => $type,
			    'tid' => $tid,
			    "is_pt"=>1
			);
			db('mall_credits')->insert($data);
			Db::execute('update long_member set `all_balance` = `all_balance` + '.$balance.' where id = '.$uid);
		}
	}
	/**
	 * 导购员提成
	 */
	function emp_change_balance($order_id,$dg_id,$dg_money){
		Db::execute('update long_line_employee set `all_balance` = `all_balance` + '.$dg_money.' where id = '.$dg_id);
	}
	/**
	 * 用户付款成功后处理
	 * @param order $order 订单信息
	 * @param user $member 用户信息
	 */
	function pay_over($order,$member){
		//获取订单详情
		$order_items = db('mall_order_item')->where('order_id', $order['id'])->select();
		
		for($num=0;$num<count($order_items);$num++){
			$field ="";
			if($order_items[$num]['goods_lanmu'] == 2){
				$field = 'agio_num';
			}else if($order_items[$num]['goods_lanmu'] == 3){
				$field = 'score_num';
			}else if($order_items[$num]['goods_lanmu'] == 5){
				$field = 'sale_num';
			}
			//减库存
			db('line_goods')->where('id', $order_items[$num]['goods_id'])->setDec($field, $order_items[$num]['number']);
			//增加销量
			db('line_goods')->where('id', $order_items[$num]['goods_id'])->setInc('sales', $order_items[$num]['number']);
		}
		
		//余额手续费
		$yongjin = bcmul($order['total_price'], 0.05, 2);
		//积分手续费
		$jifeng = bcmul($order['need_score'], 0.05, 2);
		//更新商家资金变化日志 
		$this->insbalch($order['agent_id'],'商品销售',bcsub($order['total_price'], $yongjin, 2),1,$order['id'],1);
		//更新商家积分变化日志 
		if(intval($order['give_score'])>0){
			$this->insscoch($order['agent_id'],'送积分',-$order['give_score'],1,$order['id']);
		}
		if(intval($order['need_score'])>0){
			$this->insscoch($order['agent_id'],'赚积分',bcsub($order['need_score'], $jifeng, 2),1,$order['id']);
		}
		/*if(intval($order['pay_type']) ==1){
			//扣除线上用户余额
			db('member')->where('id', $member['id'])->setDec('credit2', $order['total_price']);
		}*/
		//更新用户资金变化日志 
		$credit_data = array(
			'uid'			=> $member['id'],
			'price' 		=> -$order['total_price'],
			'add_time' 		=> now_time(),
			'credittype'	=> 'credit2',
			'operator' 		=> 0,
			'remark' 		=> '购买商品',
			'type' 			=> 0,
			'tid' 			=> $order['id'],
			"is_pt"			=>0
			);
		db('mall_credits')->insert($credit_data);
			
		if(intval($order['need_score'])>0){
			//扣除线上用户积分
			db('member')->where('id', $member['id'])->setDec('credit1', $order['need_score']);
			//扣除线下用户积分
			db('line_member')->where('mobile', $member['mobile'])->where('store_id',$order['agent_id'])->setDec('newbonusflg', $order['need_score']);
				
			//更新用户线上积分变化日志 
			$credit_data2 = array(
				'uid' 			=> $member['id'],
				'price' 		=> -$order['need_score'],
				'add_time' 		=> now_time(),
				'credittype' 	=> 'credit1',
				'operator' 		=> 0,
				'remark' 		=> '购买商品',
				'type' 			=> 0,
				'tid' 			=> $order['id'],
				'is_pt'			=>0
			);
			db('mall_credits')->insert($credit_data2);
		}
		//更新用户订单消息
		$msg_order = array(
			'uid' 			=>$order['user_id'],
			'type' 			=> 1,
			'content'		=>'订单编号：'.$order['sn'].' 付款成功',
			'create_time'	=>now_time(),
			'agent_id' 		=>0,
			'status' 		=>2	
		);
		db('message')->insert($msg_order);
		//更新商户消息
		$msg_order['agent_id'] = $order['agent_id'];
		db('message')->insert($msg_order);
	}
	
	/**
	 * 用户金额变化
	 * @param $uid 		: 用户id
	 * @param $tid 		: 店铺id
	 * @param $credittype : credit1积分credit2金钱
	 * @param $price 	: 资金变化金额,可为负数
	 * @param $remark	: 描述
	 * @param $type 	: 0.默认1.佣金2.提现3.红包4.收付款6线下消费获得积分7积分兑换
	 * @param $is_pt	: 金钱变化类型：1是合伙人分佣,0不是
	 * @param $order_id	: 订单id
	 */
	function money_change($uid,$tid,$credittype,$price,$remark,$type,$is_pt,$order_id){
		$credit_data = array(
			'uid'			=> $uid,
			'tid' 			=> $tid,
			'credittype'	=> $credittype,
			'price' 		=> $price,
			'remark' 		=> $remark,
			'type' 			=> $type,
			"is_pt"			=> 0,
			'operator' 		=> 0,
			'order_id'		=> $order_id,
			'add_time' 		=> now_time()
			);
		db('mall_credits')->insert($credit_data);
	}
	
	/**
	 * 消息通知
	 * @param $uid 		: 用户id，商户消息时此为0
	 * @param $type 	: 1订单2提现3佣金4积分5系统6付款
	 * @param $content 	: 消息内容
	 * @param $agent_id : 店铺id，用户消息时此为0
	 * @param $status	: 消息状态：1：已读，2：未读
	 */
	function msg_change($uid,$type,$content,$agent_id,$status=2){
		//更新用户订单消息
		//更新用户订单消息
		$msg_order = array(
			'uid' 			=>$uid,
			'type' 			=> $type,
			'content'		=>$content,
			'create_time'	=>$agent_id,
			'agent_id' 		=>0,
			'status' 		=>$status	
		);
		db('message')->insert($msg_order);
	}
	
	/**
	 * 用户申请vip分佣
	 * @param $user_id 	: 用户id
	 * @param $money 	: 佣金金额
	 * @param $msg 		: 系统提示消息
	 */
	function vip_yongj($user_id,$money,$msg){
		if(intval($user_id)>0){
			//更新合伙人佣金
			db('member')->where('id',$user_id)->setInc('credit3',$money); 
			//更新用户金额变化日志
			$this->money_change($user_id,0,'credit2',$money,$msg,1,1,0);
			//更新用户消息
			$this->msg_change($user_id,3,$msg,0,2);
		}else{
			//更新系统用户佣金
			db('member')->where('id',2)->setInc('credit3',$money); 
			//更新用户金额变化日志
			$this->money_change(2,0,'credit2',$money,$msg,1,1,0);
			//更新用户消息
			$this->msg_change(2,3,$msg,0,2);
		}
	}
	
	


}
